﻿using Microsoft.AspNetCore.Http;

namespace CodeIsBug.Service.Services;

/// <summary>
/// 用户service
/// </summary>
/// <param name="tokenService"></param>
/// <param name="userRepository"></param>
/// <param name="userRoleMapRepository"></param>
/// <param name="rolePermissionMapRepository"></param>
public class UserService(
    ITokenService tokenService,
    UserRepository userRepository,
    UserRoleMapRepository userRoleMapRepository,
    RolePermissionMapRepository rolePermissionMapRepository)
{
    #region 登录功能-获取token

    /// <summary>
    /// 登录功能-获取token
    /// </summary>
    /// <param name="loginInputDto"></param>
    /// <returns></returns>
    public async Task<ApiResult> Login(LoginInputDto loginInputDto)
    {
        var user = await userRepository.LoginAsync(loginInputDto);
        if (ReferenceEquals(user, null))
        {
            return new ApiResult(StatusCodes.Status200OK, "用户名或密码错误");
        }
        var userRolePermissionMap = await rolePermissionMapRepository.GetUserRolePermissionMap(user.Id);
        var roleList = await userRoleMapRepository.GetUserRoleIdsAsync(user.Id);
        var userLoginOut = new TokenData()
        {
            UserId = user.Id,
            UserName = user.UserName,
            UserAccount = user.NickName,
            UserRolesId = roleList.Select(a => a.RoleId).ToList(),
            IsSuperAdmin = roleList.Any(a => a.RoleCode?.ToLower() == "superadmin"),
            UserPermission = userRolePermissionMap
        };
        var (accessToken,refreshToken) = await tokenService.GenerateTokenAsync(userLoginOut);
        return new ApiResult(StatusCodes.Status200OK, "登录成功", new {accessToken, refreshToken });
    }

    #endregion

    #region 获取当前用户权限

    /// <summary>
    /// 获取当前用户权限
    /// </summary>
    /// <param name="token"></param>
    /// <returns></returns>
    public async Task<ApiResult> GetUserInfo(string token)
    {
        var tokenData = await tokenService.GetCurrentUserInfo();
        return new ApiResult(StatusCodes.Status200OK, "用户信息获取成功", tokenData);
    }

    #endregion
}